#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   deps.py
@Time    :   2021/02/06 19:18:13
@Author  :   superjin
@Version :   1.0
'''

from typing import Generator, Any, Union, Optional
from fastapi import Header, Depends, Request, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from db.database import SessionLocal
from setting.web import settings
from jose import exceptions, jwt
from common import casbin
from pydantic import ValidationError
from exceptions import custom_exc
import crud

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/user/login")


def check_jwt_token(
        # token: Optional[str] = Header(..., alias="authorization",description="登录token")
        token: str = Depends(oauth2_scheme)
) -> Union[str, Any]:
    try:
        payload = jwt.decode(
            token,
            settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
        )
        return payload
    except jwt.ExpiredSignatureError:
        raise custom_exc.TokenExpired()
    except (jwt.JWTError, ValidationError, AttributeError):
        raise custom_exc.TokenAuthError()


def check_authority(
        request: Request,
        payload: Optional[str] = Depends(check_jwt_token)
):
    """
    权限验证 依赖于 JWT token
    :param request:
    :param token:
    :return:
    """

    roles = payload.get("roles")
    if roles =='admin':
        return
            # 注意 字段类型都是字符串
        # 根据token中的 authority_id  请求路径  方法 判断路径
    raise custom_exc.AuthenticationError()



def get_db() -> Generator:
    """
    获取sqlalchemy会话对象
    :return:
    """
    try:
        db = SessionLocal()
        yield db
    except Exception as e:
        db.rollback()
        raise e
    finally:
        db.close()


#async def get_current_user(
#        token: str = Depends(oauth2_scheme),
#        db: Session = Depends(get_db)
#) -> user_model:
#    """
#    获取当前用户
#    :param token:
#    :return:
#    """
#    payload = check_jwt_token(token)
#    username = payload.get("username")
#    user = crud.user.get_user_by_username(db, username)
#    roles = crud.user.get_roles(user)
#    if not user:
#        raise custom_exc.UserNotFoundError()
#    return user
